<?php 
namespace App\Libs\Helper;

/**
*	Usage:高德api
*
*/	
class FindCity{
	protected static $key = 'b46c9f7416f5c483b8faf784b9f4ae22';
	protected static $output = 'json';

	//ip查询城市
	public static function getCityip($ip = ''){
		// $ip = (string)self::$request->getPost("ip");
		//ip格式为xxx.xxx.xxx.xxx
		$patt = "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/";
		$res = preg_match($patt,$ip);
		if (!$res) {
			//ip不正确
        	return \App\Libs\Views\Json::view(1, '您的ip有误', NULL);
		}else{
			//ip正确
			$arr = array(
					'ip'=>$ip,
					'output'=>self::$output,
					'key'=>self::$key
				);
			//构建参数
			$parm = http_build_query($arr);

			//构建url
			$url = 'http://restapi.amap.com/v3/ip?'.$parm;
			$cont = json_decode(file_get_contents($url),true);

			if($cont['status'] == 0){
				//获取失败
        		return \App\Libs\Views\Json::view(1, '获取城市失败,请重试', NULL);
			}else{
				if(empty($cont['city'])){
					//输入信息不符合要求未查询到
        			return \App\Libs\Views\Json::view(1, '获取城市是失败', NULL);
				}
				
				//获取成功
        		return \App\Libs\Views\Json::view(0, '获取城市成功', $cont['city']);
			}
		}
	}

	//经纬度查询城市
	public static function getCityjw($local = ''){
		// $local = (string)self::$request->getPost("local");
		//local 格式为 xxx.xxx,xxx.xxx  ,两边无空格
		$patt = "/^[-+]?([1-8]?\d{1,2}(\.\d+)?),[-+]?([1-8]?\d{1,2}(\.\d+)?)$/";
		$res = preg_match($patt,$local);
		if (!$res) {
			//经纬度不正确
        	return \App\Libs\Views\Json::view(1, '您的位置有误', NULL);
		}else{
			//经纬度正确
			$arr = array(
					'location'=>$local,
					'output'=>self::$output,
					'key'=>self::$key
				);

			//构建参数
			$parm = http_build_query($arr);

			//构建url
			$url = 'http://restapi.amap.com/v3/geocode/regeo?'.$parm;
			$cont = json_decode(file_get_contents($url),true);

			if($cont['status'] == 0){
				//获取失败
        		return \App\Libs\Views\Json::view(1, '获取城市失败,请重试', NULL);
			}else{
				//获取成功
				$prov = $cont['regeocode']['addressComponent']['province'];
				$city = $cont['regeocode']['addressComponent']['city'];

				//当所在城市为四个直辖市时，该字段返回为空,provence为直辖市名
				if (empty($city)) {
        			return \App\Libs\Views\Json::view(0, '获取城市成功', $prov);
				}else{
        			return \App\Libs\Views\Json::view(0, '获取城市成功', $city);
				}
			}
		}
	}
}

